package com.lzhpo.core.work;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzhpo.core.config.RedisUtil;
import com.lzhpo.core.domain.PrizeData;
import com.lzhpo.core.domain.ResponseObj;
import com.lzhpo.core.service.PrizeDataService;
import com.lzhpo.core.service.SumValueDataService;
import com.lzhpo.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author <a href="lijing1@wxchina.com@wxchina.com">Lijin</a>
 * @Description TODO
 * @Date 2019/12/19 14:44
 * @Version 1.0
 **/
@Slf4j
@ConditionalOnProperty(name = "data.api.switch", havingValue = "true")
@Component
public class MainWork {


    @Value("${api.schedulerboat}")
    private String schedulerboat;

    @Value("${api.clearSchduleTime}")
    private String clearSchduleTime;


    /**
     * 排列5数据接口
     */
    @Value("${api.arrage}")
    private String arrage5;

    @Value("${config.arragePeriod}")
    private long arragePeriod;

    /**
     * 保留最新的期号
     */
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;// = new ThreadPoolTaskScheduler();


    @Autowired
    private PrizeDataService prizeDataService;


    @Autowired
    private SumValueDataService sumValueDataService;


    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @PostConstruct
    public void init() {
        taskScheduler.setPoolSize(3);
        taskScheduler.setThreadNamePrefix("task-remote-request");
        taskScheduler.initialize();
        taskScheduler.schedule(new ClearDataTask(), new CronTrigger(clearSchduleTime));
    }

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void remoteApiDataFetch() {
        //生成一个任务task每隔10s去获取数据
        executorService.submit(new Arrange5());
        //获取到后取消该任务task
    }


    /**
     * 数据定期清除
     */
    private class ClearDataTask implements Runnable {

        @Override
        public void run() {
            prizeDataService.deleteDataType(DataTypeEnum.ARRANGE_FIVE.getType());

        }
    }

    private void handlerPrizeData(PrizeData prizeData) {

        if (StringUtils.isNotBlank(redisUtil.get(RedisConstant.DATA_FETCH_TERMNO_TYPE + prizeData.getTermNo()))) {
            return;
        }
        log.info("fcApi request :" + arrage5);
        log.info("福彩3D 开奖号码 resp:" + Arrays.toString(prizeData.getPrizeNums())
                + ",开奖时间：" + prizeData.getOpenTIme());

        /**
         * 设置缓存中的数据
         */
        handBeforeSave(prizeData);

        prizeDataService.handlerOriginDataTrendToDb(prizeData);
        /**
         * 保存更新不同数据类型的组后时间。
         */
        prizeDataService.updateDataTypeFecthTime(Integer.valueOf(prizeData.getType()));


    }

    /**
     * 10个数字 如果后面不足 则补 0
     *
     * @param prizeData
     */
    private void handBeforeSave(PrizeData prizeData) {
        String[] arr = prizeData.getPrizeNums();
        int size = arr.length;
        int length = 10;
        int appendSize = length - size;
        for (int i = 0; i < appendSize; i++) {
            arr = org.springframework.util.StringUtils.addStringToArray(arr, "0");
        }
        prizeData.setPrizeNums(arr);
    }


    /**
     * 排列5的数据获取线程
     */
    private class Arrange5 implements Runnable {

        @Override
        public void run() {
            try {
                List<ResponseObj> list =
                        customHttpRequest(arrage5);
                if (list.size() == 0) {
                    return;
                }
                PrizeData data = DataGeneratorUtil.parseJsonStrToPrizeData(list,
                        DataTypeEnum.ARRANGE_FIVE);
                if (DataGeneratorUtil.formatYmd.format(data.getOpenTIme()).equals(LocalDate.now().toString())) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(data.getTermNo())) {
                        handlerPrizeData(data);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                log.error("Arrange5 fetch error  {}", e);
            }
        }


    }


    private List<ResponseObj> customHttpRequest(String url) {
        //如果获取获取异常 重复三次
        List<ResponseObj> list = Lists.newArrayList();
        String bodyStr = HttpUtil.get(url);
        if (StringUtils.isBlank(bodyStr)) {
            return list;
        }
        ResponseObj obj = new ResponseObj();
        JSONArray jsonArray = JSON.parseArray(bodyStr);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        obj.setIssue(jsonObject.get("issue").toString());
        obj.setCode(jsonObject.get("code").toString());
        obj.setOpendate(jsonObject.getString("opendate"));
        list.add(obj);
        return list;
    }

}
